#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
	if(argc<2) {
		printf("usages: %s <file to lock>\n", argv[0]);
		return -1;
	}

	pid_t pid = fork();
	if(pid!=0) {
		printf("p1 is started\n");

		for(int i=0;i<10;i++) {
			FILE *lock_fp = fopen(argv[1], "a+b");
			int lock_fd = fileno(lock_fp);

			int ret=lockf(lock_fd, F_LOCK, 0);

			if(ret!=0) printf("[p1]lock failure : %d\n", ret);
			else fprintf(lock_fp, "p1[%d]\n", i);

			ret=lockf(lock_fd, F_ULOCK, 0);
			if(ret!=0) printf("[p1]unlock failure : %d\n", ret);

			fclose(lock_fp);
		}

		printf("p1 is finished\n");

		exit(0);
	}
	else {
		printf("p2 is started\n");

		for(int i=0;i<10;i++) {
			FILE *lock_fp = fopen(argv[1], "a+b");
			int lock_fd = fileno(lock_fp);

			int ret=lockf(lock_fd, F_LOCK, 0);

			if(ret!=0) printf("[p2]lock failure : %d\n", ret);
			else fprintf(lock_fp, "p2[%d]\n", i);

			ret=lockf(lock_fd, F_ULOCK, 0);
			if(ret!=0) printf("[p2]unlock failure : %d\n", ret);

			fclose(lock_fp);
		}

		printf("p2 is finished\n");

		return 0;
	}
}
